package com.osilon.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class Downloader {
	public static void download(URL url) {
		FileOutputStream output = null;
		InputStream input = null;
		
		try {
			String file = url.getFile();
			file = file.substring(file.lastIndexOf("/") + 1);
			
			URLConnection connection = url.openConnection();
			
			byte[] buffer = new byte[1024 * 8]; // 8kb buffers.
			int read = 0;
			
			output = new FileOutputStream(file);
			input = connection.getInputStream();
			
			while((read = input.read(buffer, 0, buffer.length)) > -1) {
				output.write(buffer, 0, read);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(output != null) {
				try {
					output.close();
				} catch(IOException e) {
					e.printStackTrace();
				}
			}
			
			if(input != null) {
				try {
					input.close();
				} catch(IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
